package com.liser.southernstar.utils;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES/ECB/PKCS5Padding加密
 */
public class AESEncipher {

    /**
     * 生成KEY
     */
    private static Cipher createCipher(int opmode, Key key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(opmode, key);
        return cipher;
    }

    /**
     * 加密
     * @param encodeRules 密匙
     * @param source 待加密数据
     * @return
     */
    public static byte[] jdkEncrypt(byte[] encodeRules, byte[] source) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = createCipher(Cipher.ENCRYPT_MODE, new SecretKeySpec(encodeRules, "AES"));
        return cipher.doFinal(source);
    }

    /**
     * 解密
     * @param encodeRules 密匙
     * @param encryptData 加密数据
     * @return
     */
    public static byte[] jdkDecrypt(byte[] encodeRules, byte[] encryptData) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = createCipher(Cipher.DECRYPT_MODE, new SecretKeySpec(encodeRules, "AES"));
        return cipher.doFinal(encryptData);
    }
}